<?php
	$path = __DIR__;
	$pngs = getPngs($path);
	$task = isset($_REQUEST['task']) ? $_REQUEST['task'] : null;
	$result = null;
	
	if ($task == 'png') {
		$file = $_REQUEST['file'];
		$result = renderPngHtml($file);
	} else {
		$result = renderPngList($pngs);
	}
	echo $result;
	
	/**
	*	Returns the array of PNG file names from given directory path.
	*
	*	@param $path of directory to scan
	*	@return $array of PNG filenames in given directory
	**/
	function getPngs( $path ) {
		// declare the local variables
		$result = array();
		$dir = scandir($path);
		$parts = null;
		
		// walk through the list of all files
		for($i = 0; $i < count($dir); $i++) {
			$parts = pathinfo($path . '/' . $dir[$i]);			
			// save the PNG filenames into array
			if( $parts['extension'] == 'png' ) {
				array_push($result, $dir[$i]);
			}	
		}
		
		// return the PNG files list
		return $result;
	}
	
	
	function renderPngHtml($png) {
		// declare the local variables
		$result = <<<EOD
<!doctype html>
<html>
	<head>
		<title>File: $png</title>
		<style>
			body {
				margin: 0;
				padding: 0;
			}
			#png {
				margin: 0 auto;
				display: block;
				padding:0;
			}				
		</style>
	</head>
	<body>
		<img src="$png" id='png' />	
	</body>
</html>
EOD;
		return $result;
	}
	
	
	function renderPngList($pngs) {
		// declare the local variables
		$png_html = '';
		$result = <<<EOD
<!doctype html>
<html>
	<head>
		<title>Available Layouts</title>
	</head>
	<body>
		[LIST]
	</body>
</html>
EOD;
		for($i=0; $i < count($pngs); $i++) {
			$png_html .= "<a href='index.php?task=png&file=" . urlencode($pngs[$i]) . "' title='{$pngs[$i]}'>{$pngs[$i]}</a><br/>\r";
		}
		return str_replace('[LIST]', $png_html, $result);
	}
?>